package com.LeetCode.Math;

import org.junit.Test;

/**
 * 字符串转换数字
 */
public class Atoi {
    public int myAtoi(String str) {
        int boom = Integer.MAX_VALUE/10;
        str = str.trim();
        if(str == null || str.length() == 0) return 0;
        boolean isNegative = str.charAt(0) == '-';
        boolean hasOpt = str.charAt(0) == '-' || str.charAt(0) == '+';
        int res = 0;
        int index = hasOpt ? 1 : 0;
        while(index < str.length()){
            if(str.charAt(index)<'0' || str.charAt(index)>'9')
                break;
            if(res > boom || res == boom && str.charAt(index) > '7')
                return isNegative ? Integer.MIN_VALUE : Integer.MAX_VALUE;

            res = res * 10 +(str.charAt(index++) - '0');

        }
        return isNegative ? -res : res;
    }

    @Test
    public void test(){
        System.out.println(myAtoi("42"));
        System.out.println(myAtoi("  -42"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("words and 987"));
        System.out.println(myAtoi("-91283472332"));
        System.out.println(myAtoi("-2147483649"));
    }
}
